package global.io;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.JOptionPane;


public class ReadFileWAV implements LineListener {
	private  String path;
	public void read(String path){
		this.path=path;
	}
	
    boolean playCompleted;
	private Scanner a;
    public void readfilewav() {
    	JOptionPane.showMessageDialog(null,"nhap vao duong dan den video co dinh dang WAV");
    	System.out.println("nhap file muon chay");
    	a = new Scanner(System.in);
    	this.path=a.nextLine();
    	
        File audioFile = new File(this.path);
        try {
            AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
            AudioFormat format = audioStream.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, format);
            try (Clip audioClip = (Clip) AudioSystem.getLine(info)) {
                audioClip.addLineListener(this);
     
                audioClip.open(audioStream);
                 
                audioClip.start();
                 
                while (!playCompleted) {
                    // wait for the playback completes
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                      }
                }
            }
             
        } catch (UnsupportedAudioFileException ex) {
            System.out.println("The specified audio file is not supported.");
        } catch (LineUnavailableException ex) {
            System.out.println("Audio line for playing back is unavailable.");
        } catch (IOException ex) {
            System.out.println("Error playing the audio file.");
        }        
    }   
    @Override
    public void update(LineEvent event) {
        LineEvent.Type type = event.getType();
         
        if (type == LineEvent.Type.START) {
            System.out.println("Playback started....");
             
        } else if (type == LineEvent.Type.STOP) {
            playCompleted = true;
            System.out.println("Playback completed.");
        } 
    } 
//    public static void main(String[] args) {
//        //String audioFilePath = "E:\\dungbuongtayanh.wav";
//        ReadFileWAV b = new ReadFileWAV();
//        b.play();
//    }
 
}
